import 'dart:ffi';

import 'package:card_swiper/card_swiper.dart';
import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter_rating_bar/flutter_rating_bar.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:pineapple_flutter/config/config.dart';
import 'package:pineapple_flutter/entity/hot_movie_entity.dart';
import 'package:pineapple_flutter/entity/movie_list_entity.dart';
import 'package:pineapple_flutter/entity/trailer_entity.dart';
import 'package:pineapple_flutter/routers/routers.dart';
import 'package:video_player/video_player.dart';
import '../entity/banner_entity.dart';
import '../http/api.dart';
import 'dart:convert';
import 'package:pineapple_flutter/views/vedio_controller.dart';

class HomeIndex extends StatefulWidget {
  const HomeIndex({Key? key}) : super(key: key);

  @override
  State<HomeIndex> createState() => _HomeIndexState();
}

class _HomeIndexState extends State<HomeIndex> {
  BannerEntity model = BannerEntity();
  HotMovieEntity hotModel = HotMovieEntity();
  TrailerEntity trailerModel = TrailerEntity();
  MovieListEntity listModel = MovieListEntity();
  List<ChewieController> listController = [];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    getData();
  }

  @override
  void dispose() {
    // 销毁播放器的控制器
    super.dispose();
    for (ChewieController controller in listController) {
      controller.dispose();
    }
  }

  getData() async {
    dynamic banners = await Api.getBanner();
    Map<String, dynamic> result1 = Map.from(banners);

    dynamic hots = await Api.getHotList();
    Map<String, dynamic> result2 = Map.from(hots);

    dynamic trailers = await Api.getTrailers();
    Map<String, dynamic> result3 = Map.from(trailers);

    dynamic movies = await Api.getMovieList();
    Map<String, dynamic> result4 = Map.from(movies);

    setState(() {
      model = BannerEntity.fromJson(result1);
      hotModel = HotMovieEntity.fromJson(result2);
      trailerModel = TrailerEntity.fromJson(result3);
      listModel = MovieListEntity.fromJson(result4);

      listController.clear();
      for (int i = 0; i < trailerModel.list.length; i++) {
        listController.add(VideoController.getVideoController(
            '${Config.baseUrl}${trailerModel.list[i].cover}',
            trailerModel.list[i].movieUrl));
      }
    });
  }

  //返回今日推荐item
  getListItem(String movieId, String imgurl, String title, double score) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.movieDetail,
            params: {'movieId': movieId});
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
        width: 230.w,
        child: Column(
          children: [
            ClipRRect(
              borderRadius: BorderRadius.circular(5),
              child: Image.network(
                imgurl,
                fit: BoxFit.fill,
                width: double.infinity,
                height: 290.w,
              ),
            ),
            const Padding(padding: EdgeInsets.all(2)),
            Text(
              title,
              softWrap: false,
              overflow: TextOverflow.ellipsis,
              style: TextStyle(color: (Config.colorText1), fontSize: 25.sp),
            ),
            const Padding(padding: EdgeInsets.all(2)),
            RatingBar.builder(
              itemSize: 10,
              initialRating: score,
              minRating: 1,
              direction: Axis.horizontal,
              allowHalfRating: true,
              itemCount: 5,
              ignoreGestures: true,
              itemPadding: const EdgeInsets.symmetric(horizontal: 1.0),
              itemBuilder: (context, _) => const Icon(
                Icons.star,
                color: Colors.orange,
              ),
              onRatingUpdate: (rating) {
                print(rating);
              },
            ),
          ],
        ),
      ),
    );
  }

  //返回热门预告item
  getYugaoItem(String name, String imgurl, String movieurl, int index) {
    return Padding(
      padding: EdgeInsets.fromLTRB(8.w, 0, 8.w, 0),
      child: Column(
        children: [
          Container(
            //超出部分，可裁剪
            clipBehavior: Clip.hardEdge,
            decoration: const BoxDecoration(
              borderRadius: BorderRadius.only(
                topLeft: Radius.circular(6),
                topRight: Radius.circular(6),
              ),
            ),
            width: 700.w,
            height: 350.w,
            child: Chewie(controller: listController[index]),
          ),
          Container(
            //超出部分，可裁剪
            clipBehavior: Clip.hardEdge,
            decoration: const BoxDecoration(
                borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(6),
                  bottomRight: Radius.circular(6),
                ),
                color: Config.colorMain),
            width: 700.w,
            padding: EdgeInsets.only(left: 15.w, right: 15.w),
            height: 80.w,
            child: Text(
              name,
              style: TextStyle(
                  color: Config.colorWhite, fontSize: 26.w, height: 2.5),
            ),
          ),
          Padding(padding: EdgeInsets.symmetric(vertical: 13.w))
        ],
      ),
    );
  }

  //返回猜你喜欢电影item
  getCainiItem(int index) {
    return InkWell(
      onTap: () {
        Routes.navigateTo(context, Routes.movieDetail,
            params: {'movieId': listModel.list[index].movieId});
      },
      child: Container(
        padding: EdgeInsets.fromLTRB(10.w, 0, 10.w, 0),
        child: Column(
          children: [
            Row(
              children: [
                ClipRRect(
                  borderRadius: BorderRadius.circular(5),
                  child: Image.network(
                    '${Config.baseUrl}${listModel.list[index].cover}',
                    fit: BoxFit.fill,
                    width: 198.w,
                    height: 270.w,
                  ),
                ),
                const Padding(padding: EdgeInsets.all(5)),
                SizedBox(
                  height: 270.w,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Padding(padding: EdgeInsets.all(1.w)),
                      Text(listModel.list[index].movieName,
                          style: TextStyle(
                              color: (Config.colorText1), fontSize: 32.sp)),
                      Padding(padding: EdgeInsets.all(9.w)),
                      RatingBar.builder(
                        itemSize: 12,
                        initialRating: listModel.list[index].score / 2,
                        minRating: 1,
                        direction: Axis.horizontal,
                        allowHalfRating: true,
                        itemCount: 5,
                        ignoreGestures: true,
                        itemPadding:
                            const EdgeInsets.symmetric(horizontal: 1.0),
                        itemBuilder: (context, _) => const Icon(
                          Icons.star,
                          color: Colors.orange,
                        ),
                        onRatingUpdate: (double value) {},
                      ),
                      Padding(padding: EdgeInsets.all(12.w)),
                      Text(
                        listModel.list[index].info,
                        style: TextStyle(
                            color: (Config.colorText1), fontSize: 25.sp),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      Padding(padding: EdgeInsets.all(6.w)),
                      Text(
                        '时长：${listModel.list[index].totalTime}',
                        style: TextStyle(
                            color: (Config.colorText1), fontSize: 25.sp),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                      Padding(padding: EdgeInsets.all(6.w)),
                      Text(
                        '上映时间：${listModel.list[index].releaseDate}',
                        style: TextStyle(
                            color: Config.colorText1, fontSize: 25.sp),
                        overflow: TextOverflow.ellipsis,
                        maxLines: 1,
                      ),
                    ],
                  ),
                ),
              ],
            ),
            // const Padding(padding: EdgeInsets.all(5)),
            const Divider(
              height: 20,
              thickness: 0.3,
              color: Config.colorDivider,
            ),
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        padding: const EdgeInsets.all(0),
        width: double.infinity,
        decoration: const BoxDecoration(color: Config.colorBg),
        height: double.infinity,
        child: ListView(
          scrollDirection: Axis.vertical,
          physics: const ClampingScrollPhysics(),
          padding: const EdgeInsets.all(0),
          children: [
            Stack(
              children: [
                SizedBox(
                  height: 1000.w,
                ),
                SizedBox(
                  //轮播
                  height: 800.w,
                  child: Swiper(
                    itemBuilder: (BuildContext context, int index) {
                      return Image.network(
                        '${Config.baseUrl}${model.list[index].imageUrl}',
                        fit: BoxFit.fill,
                      );
                    },
                    onTap: (index) {
                      Routes.navigateTo(context, Routes.movieDetail,
                          params: {'movieId': model.list[index].movieId});
                    },
                    autoplay: true,
                    layout: SwiperLayout.DEFAULT,
                    itemCount: model.list.length,
                    // viewportFraction: 0.7,
                    // scale: 0.8,
                    pagination: const SwiperPagination(),
                  ),
                ),
                Container(
                  margin: EdgeInsets.fromLTRB(0, 600.w, 0, 0),
                  width: double.infinity,
                  height: 200.w,
                  decoration: const BoxDecoration(
                    gradient: LinearGradient(
                      begin: Alignment.topCenter,
                      end: Alignment.bottomCenter,
                      // Add one stop for each color. Stops should increase from 0 to 1
                      stops: [0.2, 0.7],
                      colors: [
                        Colors.transparent,
                        Config.colorBg,
                      ],
                      // stops: [0.0, 0.1],
                    ),
                  ),
                ),
                Container(
                  //今日推荐
                  margin: EdgeInsets.fromLTRB(0, 530.w, 0, 0),
                  decoration: const BoxDecoration(color: Colors.transparent),
                  height: 470.w,
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Container(
                        margin: const EdgeInsets.symmetric(
                            vertical: 10, horizontal: 10),
                        child: Row(
                          children: [
                            // const Icon(Icons.local_fire_department, size: 20),
                            // const SizedBox(width: 10, height: 10),
                            Text('今日推荐',
                                style: TextStyle(
                                    color: (Config.colorText1),
                                    fontSize: 30.sp)),
                          ],
                        ),
                      ),
                      SizedBox(
                        width: double.infinity,
                        height: 380.w,
                        child: ListView.builder(
                          itemCount: hotModel.hots.length,
                          padding: const EdgeInsets.symmetric(
                              vertical: 0, horizontal: 5),
                          shrinkWrap: true,
                          scrollDirection: Axis.horizontal,
                          physics: const BouncingScrollPhysics(),
                          itemBuilder: (BuildContext context, int index) {
                            return getListItem(
                                hotModel.hots[index].movieId,
                                "${Config.baseUrl}${hotModel.hots[index].cover}",
                                hotModel.hots[index].movieName,
                                hotModel.hots[index].score / 2);
                          },
                        ),
                      ),
                    ],
                  ),
                ),
              ],
            ),
            Container(
              //热门预告片
              margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
              decoration: const BoxDecoration(color: Config.colorBg),
              height: (trailerModel.list.length * 450.w) + 100.w,
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 10),
                    child: Row(
                      children: [
                        // const Icon(Icons.local_fire_department, size: 20),
                        // const SizedBox(width: 10, height: 10),
                        Text('热门预告片',
                            style: TextStyle(
                                color: (Config.colorText1), fontSize: 30.w)),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: double.infinity,
                    height: (trailerModel.list.length * 450.w),
                    child: ListView.builder(
                      itemCount: trailerModel.list.length,
                      padding: const EdgeInsets.symmetric(
                          vertical: 0, horizontal: 5),
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return getYugaoItem(
                            trailerModel.list[index].movieName,
                            "${Config.baseUrl}${trailerModel.list[index].cover}",
                            trailerModel.list[index].movieUrl,
                            index);
                      },
                    ),
                  ),
                ],
              ),
            ),
            Container(
              //猜你喜欢
              margin: const EdgeInsets.fromLTRB(0, 10, 0, 0),
              decoration: const BoxDecoration(color: Config.colorBg),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    margin: const EdgeInsets.symmetric(
                        vertical: 10, horizontal: 10),
                    child: Row(
                      children: [
                        // const Icon(Icons.emoji_food_beverage_rounded, size: 20),
                        // const SizedBox(width: 10, height: 10),
                        Text('猜你喜欢',
                            style: TextStyle(
                                color: (Config.colorText1), fontSize: 30.w)),
                      ],
                    ),
                  ),
                  SizedBox(
                    width: double.infinity,
                    child: ListView.builder(
                      itemCount: listModel.list.length,
                      padding: const EdgeInsets.symmetric(
                          vertical: 0, horizontal: 5),
                      shrinkWrap: true,
                      scrollDirection: Axis.vertical,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (BuildContext context, int index) {
                        return getCainiItem(index);
                      },
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}
